package cn.yangliu.nacos.management.service.oauth2.impl;

import java.util.List;
import java.util.stream.Collectors;

import static cn.yangliu.nacos.management.constant.CacheConstants.GATEWAY_AUTHORITY_CACHE;

import cn.yangliu.jpa.base.service.impl.JpaServiceImpl;
import cn.yangliu.nacos.management.entity.oauth2.Oauth2Authority;
import cn.yangliu.nacos.management.repository.oauth2.Oauth2AuthorityRepository;
import cn.yangliu.nacos.management.repository.oauth2.Oauth2Role2AuthorityRepository;
import cn.yangliu.nacos.management.service.oauth2.Oauth2AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-01
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class Oauth2AuthorityServiceImpl
        extends JpaServiceImpl<Oauth2Authority,Long, Oauth2AuthorityRepository> implements Oauth2AuthorityService {

    /**
     * current class instance's member.
     * The Role 2 authority repository.
     */
    @Autowired
    private Oauth2Role2AuthorityRepository role2AuthorityRepository;

    /**
     * Sync db int.
     *
     * @param services the services
     * @return the int
     */
    @Override
    public int syncDb(List<String> services) {
        List<Oauth2Authority> authorities = repository.findAll();
        List<String> dbServices =
                authorities.stream().map(Oauth2Authority::getServiceName).collect(Collectors.toList());
        List<Oauth2Authority> unSyncAuthorities =
                services.stream()
                        .filter(service -> !dbServices.contains(service))
                        .map(Oauth2Authority::new)
                        .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(unSyncAuthorities)) {
            return 0;
        }
        repository.saveAll(unSyncAuthorities);
        return unSyncAuthorities.size();
    }

    /**
     * Delete by id.
     *
     * @param id the id
     */
    @Override
    @CacheEvict(cacheNames = GATEWAY_AUTHORITY_CACHE, allEntries = true)
    public void deleteById(Long id) {
        role2AuthorityRepository.deleteByAuthorityId(id);
        super.deleteById(id);
    }
}
